package com.xinxing.learning.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinxing.learning.security.filter.LoginCaptchaFilter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;

import java.util.HashMap;

@Slf4j
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin", "supper").build());
        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @SneakyThrows
    @Bean
    public LoginCaptchaFilter loginCaptchaFilter() {
        LoginCaptchaFilter loginCaptchaFilter = new LoginCaptchaFilter();
        loginCaptchaFilter.setFilterProcessesUrl("/doLogin");
        loginCaptchaFilter.setUsernameParameter("uname");
        loginCaptchaFilter.setPasswordParameter("pwd");
        loginCaptchaFilter.setCaptchaParameter("captcha");

        loginCaptchaFilter.setAuthenticationManager(authenticationManager());
        loginCaptchaFilter.setAuthenticationSuccessHandler((request, response, authentication) -> {
            HashMap<String, Object> result = new HashMap<>();
            result.put("msg", "登录成功");
            result.put("status", HttpStatus.OK.value());
            result.put("authentication", authentication);
            response.setContentType("application/json;charset=UTF-8");
            String resultStr = new ObjectMapper().writeValueAsString(result);
            log.info("onAuthenticationSuccess() returned: " + resultStr);
            response.getWriter().println(resultStr);
        });
        loginCaptchaFilter.setAuthenticationFailureHandler((request, response, exception) -> {
            HashMap<String, Object> result = new HashMap<>();
            result.put("msg", "登录失败: " + exception.getMessage());
            result.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
            String resultStr = new ObjectMapper().writeValueAsString(result);
            log.info("onAuthenticationFailure() returned: " + resultStr);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(resultStr);
        });
        return loginCaptchaFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/captcha").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((req, resp, ex) -> {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("msg", "请先登录");
                    result.put("status", HttpStatus.UNAUTHORIZED.value());
                    resp.setContentType("application/json;charset=UTF-8");
                    String resultStr = new ObjectMapper().writeValueAsString(result);
                    log.info("onAuthenticationSuccess() returned: " + resultStr);
                    resp.getWriter().println(resultStr);
                })
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutRequestMatcher(new OrRequestMatcher(
                        new AntPathRequestMatcher("/logout", "GET"),
                        new AntPathRequestMatcher("/logout", "POST")
                ))
                .logoutSuccessHandler((req, resp, authentication) -> {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("msg", "注销成功");
                    result.put("status", 200);
                    result.put("authentication", authentication);
                    resp.setContentType("application/json;charset=UTF-8");
                    String resultStr = new ObjectMapper().writeValueAsString(result);
                    log.info("onAuthenticationSuccess() returned: " + resultStr);
                    resp.getWriter().println(resultStr);
                })
                .and()
                .csrf().disable()
        ;

        http.addFilterAt(loginCaptchaFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
